package com.yuno.mock.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

/**
 * 线程池管理器
 * 
 * @author yuno
 * @since 2024-01-01
 */
public class ThreadPoolManager {
    
    private static final Logger log = LoggerFactory.getLogger(ThreadPoolManager.class);
    
    // 默认线程池配置
    private static final int DEFAULT_CORE_POOL_SIZE = 4;
    private static final int DEFAULT_MAX_POOL_SIZE = 8;
    private static final long DEFAULT_KEEP_ALIVE_TIME = 60L;
    private static final int DEFAULT_QUEUE_CAPACITY = 100;
    
    // 全局线程池实例
    private static volatile ThreadPoolExecutor executor;
    
    // 私有构造函数，防止实例化
    private ThreadPoolManager() {
    }
    
    /**
     * 获取线程池执行器
     */
    public static ThreadPoolExecutor getExecutor() {
        if (executor == null) {
            synchronized (ThreadPoolManager.class) {
                if (executor == null) {
                    executor = createThreadPool();
                }
            }
        }
        return executor;
    }
    
    /**
     * 创建线程池
     */
    private static ThreadPoolExecutor createThreadPool() {
        log.info("创建线程池 - 核心线程数: {}, 最大线程数: {}, 队列容量: {}", 
                DEFAULT_CORE_POOL_SIZE, DEFAULT_MAX_POOL_SIZE, DEFAULT_QUEUE_CAPACITY);
        
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
            DEFAULT_CORE_POOL_SIZE,
            DEFAULT_MAX_POOL_SIZE,
            DEFAULT_KEEP_ALIVE_TIME,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(DEFAULT_QUEUE_CAPACITY),
            new ThreadFactory() {
                private int threadNumber = 1;
                
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r, "ExcelReader-" + threadNumber++);
                    thread.setDaemon(false);
                    return thread;
                }
            },
            new ThreadPoolExecutor.CallerRunsPolicy()
        );
        
        // 允许核心线程超时
        pool.allowCoreThreadTimeOut(true);
        
        return pool;
    }
    
    /**
     * 获取活跃线程数
     */
    public static int getActiveCount() {
        ThreadPoolExecutor executor = getExecutor();
        return executor.getActiveCount();
    }
    
    /**
     * 获取当前线程池大小
     */
    public static int getPoolSize() {
        ThreadPoolExecutor executor = getExecutor();
        return executor.getPoolSize();
    }
    
    /**
     * 获取线程池状态
     */
    public static Map<String, Object> getStatus() {
        if (executor == null) {
            Map<String, Object> status = new HashMap<>();
            status.put("initialized", false);
            return status;
        }
        
        Map<String, Object> status = new HashMap<>();
        status.put("initialized", true);
        status.put("corePoolSize", executor.getCorePoolSize());
        status.put("maximumPoolSize", executor.getMaximumPoolSize());
        status.put("activeCount", executor.getActiveCount());
        status.put("poolSize", executor.getPoolSize());
        status.put("largestPoolSize", executor.getLargestPoolSize());
        status.put("taskCount", executor.getTaskCount());
        status.put("completedTaskCount", executor.getCompletedTaskCount());
        status.put("queueSize", executor.getQueue().size());
        status.put("queueRemainingCapacity", executor.getQueue().remainingCapacity());
        status.put("isShutdown", executor.isShutdown());
        status.put("isTerminated", executor.isTerminated());
        
        return status;
    }
    
    /**
     * 提交任务
     */
    public static <T> Future<T> submit(Callable<T> task) {
        return getExecutor().submit(task);
    }
    
    /**
     * 提交任务
     */
    public static Future<?> submit(Runnable task) {
        return getExecutor().submit(task);
    }
    
    /**
     * 执行任务
     */
    public static void execute(Runnable task) {
        getExecutor().execute(task);
    }
    
    /**
     * 关闭线程池
     */
    public static void shutdown() {
        if (executor != null) {
            log.info("开始关闭线程池");
            executor.shutdown();
            try {
                // 等待60秒让任务完成
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    log.warn("线程池未能在60秒内正常关闭，强制关闭");
                    executor.shutdownNow();
                    // 再等待60秒
                    if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                        log.error("线程池无法关闭");
                    }
                }
            } catch (InterruptedException e) {
                log.error("等待线程池关闭时被中断", e);
                executor.shutdownNow();
                Thread.currentThread().interrupt();
            }
            log.info("线程池已关闭");
        }
    }
    
    /**
     * 立即关闭线程池
     */
    public static void shutdownNow() {
        if (executor != null) {
            log.info("立即关闭线程池");
            executor.shutdownNow();
        }
    }
    
    /**
     * 检查线程池是否健康
     */
    public static boolean isHealthy() {
        if (executor == null) {
            return false;
        }
        
        // 检查线程池是否正常运行
        if (executor.isShutdown() || executor.isTerminated()) {
            return false;
        }
        
        // 检查队列是否过载
        int queueSize = executor.getQueue().size();
        int queueCapacity = DEFAULT_QUEUE_CAPACITY;
        double queueUsage = (double) queueSize / queueCapacity;
        
        if (queueUsage > 0.8) {
            log.warn("线程池队列使用率过高: {}%", queueUsage * 100);
        }
        
        return queueUsage < 0.9; // 队列使用率超过90%认为不健康
    }
    
    /**
     * 调整线程池大小
     */
    public static void adjustPoolSize(int corePoolSize, int maximumPoolSize) {
        if (executor != null) {
            log.info("调整线程池大小 - 核心线程数: {} -> {}, 最大线程数: {} -> {}", 
                    executor.getCorePoolSize(), corePoolSize,
                    executor.getMaximumPoolSize(), maximumPoolSize);
            
            executor.setCorePoolSize(corePoolSize);
            executor.setMaximumPoolSize(maximumPoolSize);
        }
    }
    
    /**
     * 获取线程池统计信息
     */
    public static String getStatistics() {
        if (executor == null) {
            return "线程池未初始化";
        }
        
        return String.format(
            "线程池统计 - 活跃线程: %d/%d, 队列任务: %d/%d, 已完成: %d, 总任务: %d",
            executor.getActiveCount(),
            executor.getPoolSize(),
            executor.getQueue().size(),
            DEFAULT_QUEUE_CAPACITY,
            executor.getCompletedTaskCount(),
            executor.getTaskCount()
        );
    }
}